package com.sr.srinterpolation.util;

public class LatexUtil {
    // 生成Latex公式字符串
    public static String creatLatexString(int[][] polynomial) {
        if (polynomial == null || polynomial.length != 2) {
            return "";
        }
        int n = polynomial[0].length;
        // 判断每行显示几项
        int countPerRow = n % 3 / 3.0 > n % 4 / 4.0 ? 3 : 3;
        // Latex
        String header = "${\\Huge ";
        String footer = "}$";
        StringBuilder sb = new StringBuilder(header);
        boolean isFirst = true;
        for (int i = n - 1, j = 0; i >= 0; i--) {
            int num = polynomial[0][i];
            int den = polynomial[1][i];
            // 分子为0则跳过这一项
            if (num == 0) {
                continue;
            }
            // 判断是否为第一项
            if (isFirst) {
                isFirst = false;
                // 添加符号
                if (num < 0) {
                    sb.append("-");
                }
            } else {
                // 判断是否需要换行显示
                if (j >= countPerRow) {
                    j = 0;
                    sb.append(footer).append('\n').append(header);
                }
                // 添加符号
                sb.append(num < 0 ? "-" : "+");
            }
            // 添加该项系数
            int absNum = Math.abs(num);
            if (den == 1) {
                sb.append(absNum);
            } else {
                sb.append("\\frac{").append(absNum).append("}{").append(den).append('}');
            }
            // 添加x部分
            if (i > 1) {
                sb.append("x^").append(i);
            } else if (i == 1) {
                sb.append('x');
            }
            // 计数
            j++;
        }
        sb.append(footer);
        return sb.toString();
    }

    // 生成验算字符串
    public static String createCheckingString(int[][] polynomial) {
        if (polynomial == null || polynomial.length != 2) {
            return "";
        }
        String header = "${\\Huge ";
        String footer = "}$";
        StringBuilder sb = new StringBuilder(header);
        int n = polynomial[0].length;
        for (int i = 1, j = 0; i <= n; i++, j++) {
            // 判断是否需要换行显示
            if (j >= 2) {
                j = 0;
                sb.append(footer).append('\n').append(header);
            }
            // 计算结果
            double result = 0;
            for (int u = 0; u < n; u++) {
                result += 1.0 * polynomial[0][u] / polynomial[1][u] * Math.pow(i, u);
            }
            sb.append("f(").append(i).append(")=").append(Math.round(result)).append("\\quad ");
        }
        sb.append(footer);
        return sb.toString();
    }
}
